from flask import render_template, g, session, jsonify, request, redirect, current_app

from info import db, redis_store
from info.models import Order, House
from info.modules.orders import orders_blu

from info.utils.common import user_login
from info.utils.response_code import RET


@orders_blu.route("/", methods=['GET', 'PUT'])
@user_login
def order():
    if request.method == 'GET':

        user = g.user
        role = request.args.get('role')

        if not user:
            return redirect('/login')

        if not role:
            return jsonify(errno=RET.PARAMERR, errmsg='没有参数')

        if role not in ['landlord', 'custom']:
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

        if role == 'custom':

            try:
                orders = Order.query.filter(Order.user_id == user.id).order_by(Order.create_time.desc()).all()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR,errmsg="查询用户订单错误")

            orders_dict_li =[]
            if orders:
                orders_dict_li =[order.to_dict() for order in orders]

            return jsonify(errno=RET.OK, errmsg='OK', data={"orders":orders_dict_li })
        elif role == 'landlord':
            try:
                houses = House.query.filter(House.user_id == user.id).all()
            except Exception as e:
                return jsonify(errno=RET.DBERR, errmsg='数据库错误')
            if not houses:
                return jsonify(errno=RET.DATAERR, errmsg='没有房屋信息')
            # 我的房屋 id
            house_id = [house.id for house in houses]
            #
            # # 所有订单 id
            # orders = Order.query.all()
            # order_ids = [order.house_id for order in orders]
            #
            # # 我的房源 成为订单 的 id
            # customs_order_ids = list(set(house_id) & set(order_ids))
            #
            # orders = [Order.query.filter(Order.house_id == customs_order_id).to_dict() for customs_order_id in customs_order_ids]

            order_obj = Order.query.filter(Order.house_id.in_(house_id)) \
                .order_by(Order.create_time.desc()).all()
            orders = [order.to_dict() for order in order_obj]
            data = {
                "orders": orders
            }
            return jsonify(errno=RET.OK, errmsg='Ok', data=data)

    # elif request.method == 'PUT':
    #     action = request.json.get('action')
    #     order_id = request.json.get('order_id')
    #     if not all([action, order_id]):
    #         return jsonify(errno=RET.PARAMERR, errmsg='参数不全')
    #     try:
    #         order_id = int(order_id)
    #     except Exception as e:
    #         return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    #     if action == "accep":
    #         try:
    #             order = Order.query.get(order_id)
    #         except Exception as e:
    #             return jsonify(errno=RET.DBERR, errmsg='数据库错误')
    #         if not order:
    #             return jsonify(errno=RET.DATAEXIST, errmsg='数据不存在')
    #         order.status = "WAIT_COMMENT"
    #         try:
    #             db.session.commit()
    #         except Exception as e:
    #             db.session.rollback()
    #             return jsonify(errno=RET.DBERR, errmsg='数据库错误')
    #
    #     elif action == "reject":
    #         reason = request.json.get('reason')
    #         if not reason:
    #             return jsonify(errno=RET.PARAMERR, errmsg='参数不全')
    #         try:
    #             order = Order.query.get(order_id)
    #         except Exception as e:
    #             return jsonify(errno=RET.DBERR, errmsg='数据库错误')
    #         if not order:
    #             return jsonify(errno=RET.DATAEXIST, errmsg='数据不存在')
    #         order.status = "REJECTED"
    #         order.comment = reason
    #         try:
    #             db.session.commit()
    #         except Exception as e:
    #             db.session.rollback()
    #             return jsonify(errno=RET.DBERR, errmsg='数据库错误')


@orders_blu.route('/comment', methods=['PUT'])
@user_login
def save_orders_comment():

    # 获取参数
    order_id = request.json.get('order_id')
    data_dict = request.json
    comment = data_dict.get('comment')

    if not comment:
        return jsonify(errno=RET.DBERR,errmsg='参数错误')

    # 需要确保只能评论自己下的订单，而且订单处于待评价状态才可以
    try:
        order = Order.query.filter(Order.id==order_id,Order.status=='WAIT_COMMENT').first()
        house = order.house
    except Exception as e:
        print('查询订单信息出错_%s'%e)
        return jsonify(errno=RET.DBERR,errmsg='数据库错误')

    if not order:
        return jsonify(errno=RET.DBERR,errmsg='无法获取订单信息')

    try:
        # 将订单的状态设置为已完成
        order.status = 'COMPLETE'
        order.comment = comment
        house.order_count += 1
        # db.session.add(order)
        # db.session.add(house)
        db.session.commit()
    except Exception as e:
        print('保存数据错误_%s'%e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据异常')

    # 因为房屋详情中有订单的评价信息，为了让最新的评价信息展示在房屋详情中，所以删除redis中关于本订单房屋的详情缓存
    # try:
    #     redis_store.delete('house_detail_%s'%order.house.id)
    # except Exception as e:
    #     print('删除缓存错误_%s'%e)

    return jsonify(errno=RET.OK,errmsg='OK')




